import {getUserInfo, setUserMobile} from "@/api/bill/user/api.js";
import {
  addCompanyAdmin,
  addCompanyUserByNameOrEmailOrMobile,
  createCompany,
  deleteCompanyUser,
  getCompanyUserList, removeCompanyAdmin
} from "@/api/bill/company/api.js";
import {elTip, explainAccount} from "@/utils/index.js";
import {CompanyRole} from "@/roleTypes/company.js";

// -----------------------------------------------------------1---------------------------------------------------------------------------------------
//  获取公司列表
const companyList = ref([]);

export const useCompanyListRef = () => {
  return companyList;
};
// 创建新公司
export const useCreateCompany = async (companyName) => {
  const newCompany = (await createCompany(localStorage['id'], companyName)).company;
  let index = companyList.value.length + 1;
  let companyListTemp = [...companyList.value];
  companyListTemp.push({
    role: newCompany.role,
    companyId: newCompany.company_id,
    name: newCompany.companyName,
    index: index
  });
  companyList.value = companyListTemp;
};

export const useGetCompanyId = (companyName) => {
  for (let i = 0; i < companyList.value.length; i++) {
    if (companyList.value[i].name === companyName) {
      return companyList.value[i].companyId;
    }
  }
  return -1;
};

// -----------------------------------------------------------2---------------------------------------------------------------------------------------
//  获取用户信息
const userInfo = ref({
  id: -1,
  username: '',
  email: '',
  isCompany: false,
  mobile: '',
  companyList: []
});
/**
 * 获取用户信息
 */
export const useInitUserInfo = async () => {
  if (!localStorage['id']) {
    requestAnimationFrame(useInitUserInfo);
    return;
  }
  watchEffect(() => {
    let companys = [];
    let index = 1;
    if (userInfo.value.companyList.length === 0) {
      return;
    }
    userInfo.value.companyList.forEach(item => {
      companys.push({
        role: item.role,
        companyId: item.company_id,
        name: item.companyName,
        index: index++
      });
    });
    companyList.value = companys;
  });
  let userInfoRes = await getUserInfo(localStorage["id"]);
  let userInfoTemp = {};
  userInfoTemp.companyList = userInfoRes.companyList;
  userInfoTemp.isCompany = !!userInfoRes.is_company;
  userInfoTemp.username = userInfoRes.user_name;
  userInfoTemp.email = userInfoRes.email;
  userInfoTemp.id = userInfoRes.id;
  userInfoTemp.mobile = userInfoRes.mobile;
  userInfo.value = userInfoTemp;

};

export const useUserInfoRef = () => {
  return userInfo;
};

export const useUpdateUserMobile = async (newMobile) => {
  await setUserMobile(localStorage["id"], newMobile);
  userInfo.value.mobile = newMobile;
};

requestAnimationFrame(useInitUserInfo);

// -----------------------------------------------------------3---------------------------------------------------------------------------------------
// 获取公司员工
const companyUserRef = ref({});

const useInitCompanyUserList = async () => {
  if (companyList.value.length === 0 || !localStorage['id']) {
    requestAnimationFrame(useInitCompanyUserList);
    return;
  }
  let companyUserTemp = {};
  for (let index = 0; index < companyList.value.length; index++) {
    const company = companyList.value[index];
    let res = await getCompanyUserList(localStorage['id'], company.companyId);
    companyUserTemp[company.companyId] = res.companyUserList.map(item => {
      return {
        "companyId": item.company_id,
        "role": item.role,
        "userId": item.user_id,
        "username": item.user_name,
        "email": item.email,
        'mobile': item.mobile,
      };
    });
  }
  companyUserRef.value = companyUserTemp;
};

// 获取公司的员工响应式对象 并且将对象缓存起来
const companyUserRefTemp = {};
export const useGetCompanyUserListRef = (companyId) => {
  if (companyUserRefTemp[companyId]) {
    return companyUserRefTemp[companyId];
  }
  const resRef = ref([]);
  watch(() => companyUserRef.value, (newValue) => {
    if (!newValue[companyId]) {
      return;
    }
    resRef.value = [...newValue[companyId]];
  }, {immediate: true, deep: true});
  companyUserRefTemp[companyId] = resRef;
  return resRef;
};

// 删除公司员工
export const useDeleteCompanyUser = async (companyId, userId) => {
  await deleteCompanyUser(localStorage['id'], companyId, userId);
  companyUserRef.value[companyId] = companyUserRef.value[companyId].filter(item => item.userId !== userId);
};

// 添加公司员工
export const useAddCompanyUser = async (companyId, data) => {
  // 判断数据新员工输入框数据是名称还是邮箱
  if(!data) {
    return elTip('请输入用户名或邮箱', 'error');
  }
  let {username, email, mobile} = explainAccount(data);
  let newCompanyUser = (await addCompanyUserByNameOrEmailOrMobile(localStorage['id'], companyId, username, email, mobile)).user;
  let companyUserTemp = [...companyUserRef.value[companyId]];
  companyUserTemp.push({
    "companyId": newCompanyUser.company_id,
    "role": newCompanyUser.role,
    "userId": newCompanyUser.user_id,
    "username": newCompanyUser.user_name,
    "email": newCompanyUser.email,
    'mobile': newCompanyUser.mobile,
  });
  companyUserRef.value[companyId] = companyUserTemp;
};

requestAnimationFrame(useInitCompanyUserList);

// -----------------------------------------------------------4---------------------------------------------------------------------------------------
// 获取公司员工的职位 使用缓存缓存起来
let userRoleRef = {};
export const useGetCompanyUserRoleRef = (companyId, userId) => {
  if (userRoleRef[`${companyId}-${userId}`]) {
    return userRoleRef[`${companyId}-${userId}`];
  }
  // 获取公司员工职位
  let companyUserListTemp = useGetCompanyUserListRef(companyId);
  let myRoleRef = computed(() => {
    return companyUserListTemp.value.find(item => item.userId === Number(userId))?.role || 3;
  });
  userRoleRef[`${companyId}-${userId}`] = myRoleRef;
  return myRoleRef;
};

// 设置员工为管理员
export const useSetCompanyUserAdmin = async (companyId, userId) => {
  await addCompanyAdmin(localStorage['id'], companyId, userId);
  let companyUserListTemp = companyUserRef.value[companyId];
  let companyUserTemp = companyUserListTemp.find(item => item.userId === Number(userId));
  companyUserTemp.role = CompanyRole.ADMIN;
};

// 设置员工为普通员工 移除管理员
export const useRemoveCompanyUserAdmin = async (companyId, userId) => {
  await removeCompanyAdmin(localStorage['id'], companyId, userId);
  let companyUserListTemp = companyUserRef.value[companyId];
  let companyUserTemp = companyUserListTemp.find(item => item.userId === Number(userId));
  companyUserTemp.role = CompanyRole.MEMBER;
};
